namespace DotNetNuke.HttpModules
{
    using DotNetNuke.Common;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.HttpModules.Config;
    using Microsoft.VisualBasic;
    using System;
    using System.Collections;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Text.RegularExpressions;
    using System.Web;

    public class UrlRewriteModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(this.OnBeginRequest);
        }

        public void OnBeginRequest(object s, EventArgs e)
        {
            HttpApplication app = (HttpApplication) s;
            string requestedPath = app.Request.Url.AbsolutePath;
            HttpServerUtility Server = app.Server;
            HttpRequest Request = app.Request;
            HttpResponse Response = app.Response;
            string strURL = Request.Url.AbsolutePath;
            string strDoubleDecodeURL = Server.UrlDecode(Server.UrlDecode(Request.RawUrl));
            if ((strURL.IndexOf("..") != -1) | (strDoubleDecodeURL.IndexOf("..") != -1))
            {
                throw new HttpException(0x194, "Not Found");
            }
            if ((Request.Path.IndexOf('\\') >= 0) | (Path.GetFullPath(Request.PhysicalPath) != Request.PhysicalPath))
            {
                throw new HttpException(0x194, "Not Found");
            }
            if (!Request.Url.LocalPath.ToLower().EndsWith("install.aspx"))
            {
                PortalAliasInfo objPortalAliasInfo;
                app.Context.Items.Add("UrlRewrite:OriginalUrl", app.Request.Url.AbsoluteUri);
                RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
                int refIntHelperL0 = rules.Count - 1;
                for (int i = 0; i <= refIntHelperL0; i++)
                {
                    Regex re = new Regex("^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$", RegexOptions.IgnoreCase);
                    if (re.IsMatch(requestedPath))
                    {
                        string sendTo = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));
                        string sesUrlParams = re.Match(requestedPath).Groups[2].Value;
                        if (sesUrlParams.Trim().Length > 0)
                        {
                            string[] urlParams = sesUrlParams.Replace(@"\", "/").Split(new char[] { '/' });
                            int refIntHelperL1 = urlParams.Length - 1;
                            for (int x = 1; x <= refIntHelperL1; x++)
                            {
                                if ((urlParams[x].Trim().Length > 0) & (urlParams[x].ToLower() != "Default.aspx".ToLower()))
                                {
                                    sendTo = sendTo + "&" + urlParams[x].Replace(".aspx", "").Trim() + "=";
                                    if (x < (urlParams.Length - 1))
                                    {
                                        x++;
                                        if (urlParams[x].Trim() != "")
                                        {
                                            sendTo = sendTo + urlParams[x].Replace(".aspx", "");
                                        }
                                    }
                                }
                            }
                        }
                        RewriterUtils.RewriteUrl(app.Context, sendTo);
                        break;
                    }
                }
                int TabId = -1;
                int PortalId = -1;
                string DomainName = null;
                string PortalAlias = null;
                if (Request.QueryString["tabid"] != null)
                {
                    TabId = int.Parse(Request.QueryString["tabid"]);
                }
                if (Request.QueryString["portalid"] != null)
                {
                    PortalId = int.Parse(Request.QueryString["portalid"]);
                }
                if ((Request.QueryString["alias"] != null) && (PortalSettings.GetPortalAliasInfo(Request.QueryString["alias"]) != null))
                {
                    if (Strings.InStr(1, Request.QueryString["alias"], DomainName, CompareMethod.Text) == 0)
                    {
                        Response.Redirect(DotNetNuke.Common.Globals.GetPortalDomainName(Request.QueryString["alias"], Request, true), true);
                    }
                    else
                    {
                        PortalAlias = Request.QueryString["alias"];
                    }
                }
                DomainName = DotNetNuke.Common.Globals.GetDomainName(Request);
                if ((PortalAlias == null) && (PortalId != -1))
                {
                    PortalAlias = PortalSettings.GetPortalByID(PortalId, DomainName);
                }
                if ((PortalAlias == null) && (TabId != -1))
                {
                    PortalAlias = PortalSettings.GetPortalByTab(TabId, DomainName);
                    if ((PortalAlias == null) | (PortalAlias == ""))
                    {
                        objPortalAliasInfo = PortalSettings.GetPortalAliasInfo(DomainName);
                        if (objPortalAliasInfo != null)
                        {
                            if (app.Request.Url.AbsoluteUri.ToLower().StartsWith("https://"))
                            {
                                strURL = "https://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            else
                            {
                                strURL = "http://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            if (strURL.ToLower().IndexOf(DomainName.ToLower()) == -1)
                            {
                                strURL = strURL + app.Request.Url.PathAndQuery;
                            }
                            Response.Redirect(strURL, true);
                        }
                    }
                }
                if ((PortalAlias == null) | (PortalAlias == ""))
                {
                    PortalAlias = DomainName;
                }
                objPortalAliasInfo = PortalSettings.GetPortalAliasInfo(PortalAlias);
                if (objPortalAliasInfo != null)
                {
                    PortalId = objPortalAliasInfo.PortalID;
                }
                if (PortalId == -1)
                {
                    if (!Request.Url.LocalPath.ToLower().EndsWith("Default.aspx".ToLower()))
                    {
                        return;
                    }
                    if (Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostPortalId"])) != "")
                    {
                        PortalId = Convert.ToInt32(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostPortalId"]));
                        ArrayList arrPortalAliases = new PortalAliasController().GetPortalAliasArrayByPortalID(int.Parse(Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostPortalId"]))));
                        if (arrPortalAliases.Count > 0)
                        {
                            objPortalAliasInfo = (PortalAliasInfo) arrPortalAliases[0];
                            if (app.Request.Url.AbsoluteUri.ToLower().StartsWith("https://"))
                            {
                                strURL = "https://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            else
                            {
                                strURL = "http://" + objPortalAliasInfo.HTTPAlias.Replace("*.", "");
                            }
                            if (TabId != -1)
                            {
                                strURL = strURL + app.Request.Url.Query;
                            }
                            Response.Redirect(strURL, true);
                        }
                    }
                }
                if (PortalId != -1)
                {
                    DotNetNuke.Common.Globals.SetApplicationName(PortalId);
                    PortalSettings _portalSettings = new PortalSettings(TabId, objPortalAliasInfo);
                    app.Context.Items.Add("PortalSettings", _portalSettings);
                }
                else
                {
                    StreamReader objStreamReader = File.OpenText(Server.MapPath("~/404.htm"));
                    string strHTML = objStreamReader.ReadToEnd();
                    objStreamReader.Close();
                    strHTML = Strings.Replace(strHTML, "[DOMAINNAME]", DomainName, 1, -1, CompareMethod.Binary);
                    Response.Write(strHTML);
                    Response.End();
                }
            }
        }

        public string ModuleName
        {
            get
            {
                return "UrlRewriteModule";
            }
        }
    }
}

